<?php
/**
 *
 */
class ItemsController extends AppController {

	//public $uses = array('Group', 'User');

	public $helpers = array('Html', 'Form');

	public function isAuthorized($user) {
		return true;
	}

	public function index() {
		$user_logged = array('id' => $this->Auth->user('id_user'));
		$this->set('user_logged', $user_logged);
		//We are taking all the file from items where the user connected is the owner
		$result = $this->Item->query('SELECT * FROM items WHERE items.id_owner= ' . (int)$this->Auth->user('id_user'));
		$this->set('own_files', $result);
		//We are taking all the file shared with the connected user
		$result2 = $this->Item->query('SELECT items.*, users.name FROM items, items_users, users 
				WHERE items_users.id_file=items.id_file AND items_users.id_user= ' . (int)$this->Auth->user('id_user').' AND items.id_owner=users.id_user');
		$this->set('single_files', $result2);
		//we are taking all the file shared to a group connected to the user | by Kamel
		//Request from DB all the files that are shared with a group in which I'm a member. | improvement by Kęstutis
		//Request from DB all the files that are shared within group members you are. | improvement by Kastytis
		$result3 = $this->Item->query('SELECT items.*, groups.group_name FROM items, groups_items, groups 
			WHERE items.id_file=groups_items.id_file AND groups_items.id_group IN (SELECT id_group FROM groups_users WHERE groups_users.id_user= ' . (int)$this->Auth->user('id_user') . ') AND groups_items.id_group=groups.id_group');
		$this->set('groups_files', $result3);
	}

	/**
	 * uploads files to the server
	 * @params:
	 *      $folder     = the folder to upload the files e.g. 'img/files'
	 *      $formdata   = the array containing the form files
	 *      $itemId     = id of the item (optional) will create a new sub folder
	 * @return:
	 *      will return an array with the success of each file upload
	 */
	function add_file($itemId = null) {
		if (isset($_GET['uid'])) {
			//SAVING ON DROPBOX

			$result = $this->Item->query('SELECT file_name FROM items WHERE id_owner="' . $this->Auth->user('id_user') . '" ORDER BY created DESC LIMIT 1');

			// Require the bootstrap
			require_once ('bootstrap.php');
			// Create a temporary file and write some data to it
			$tmp = tempnam('/tmp', 'dropbox');
			//pr($result);
			$data = file_get_contents('file/' . $result[0]['items']['file_name']);
			file_put_contents($tmp, $data);

			// Upload the file with an alternative filename
			$put = $dropbox->putFile($tmp, $result[0]['items']['file_name']);

			// Unlink the temporary file
			unlink($tmp);

			// Dump the output

			//die();
			//$this->redirect('index');
		} else {
			if (!empty($this->data) && is_uploaded_file($this->data['Item']['File']['tmp_name'])) {
				// setup dir names absolute and relative
				$folder_url = './file';
				$rel_url = $folder_url;
				// create the folder if it does not exist
				if (!is_dir($folder_url))
					mkdir($folder_url);

				$file = $this->data['Item']['File'];
				// loop through and deal with the files
				// replace spaces with underscores
				$filename = str_replace(' ', '_', $file['name']);
				// assume filetype is true
				$typeOK = true;

				// if file type ok upload the file
				if ($typeOK) {
					// switch based on error code
					switch($file['error']) {
						case 0 :
							// check filename already exists
							if (!file_exists($folder_url . '/' . $filename)) {
								// create full filename
								$full_url = $folder_url . '/' . $filename;
								$url = $rel_url . '/' . $filename;
								// upload the file
								$success = move_uploaded_file($file['tmp_name'], $url);
							} else {
								// create unique filename and upload file
								ini_set('date.timezone', 'Europe/London');
								$now = date('Y-m-d-His');
								$full_url = $folder_url . '/' . $now . $filename;
								$url = $rel_url . '/' . $now . $filename;
								$success = move_uploaded_file($file['tmp_name'], $url);
							}
							// if upload was successful
							if ($success) {
								// save the url of the file
								$result['urls'][] = $url;
								$this->request->data['Item']['file_name'] = (isset($now) ? $now : '').$this->data['Item']['File']['name'];
								$this->request->data['Item']['type'] = $this->data['Item']['File']['type'];
								$this->request->data['Item']['size'] = $this->data['Item']['File']['size'];
								$this->request->data['Item']['id_owner'] = $this->Auth->user('id_user');
								$this->Item->save($this->data);

								if (isset($this->request->data['Item']['dropbox'])){
									// Require the bootstrap
									require_once ('bootstrap.php');
									// Create a temporary file and write some data to it
									$tmp = tempnam('/tmp', 'dropbox');
									//pr($result);
									$data = file_get_contents('file/' . $this->request->data['Item']['file_name']);
									file_put_contents($tmp, $data);
	
									// Upload the file with an alternative filename
									$put = $dropbox->putFile($tmp, $this->request->data['Item']['file_name']);
	
									// Unlink the temporary file
									unlink($tmp);
								}

							} else {
								$result['errors'][] = "Error uploaded $filename. Please try again.";
							}
							break;
						case 3 :
							// an error occurred
							$result['errors'][] = "Error uploading $filename. Please try again.";
							break;
						default :
							// an error occurred
							$result['errors'][] = "System error uploading $filename. Contact webmaster.";
							break;
					}
				} elseif ($file['error'] == 4) {
					// no file was selected for upload
					$result['nofiles'][] = "No file Selected";
				} else {
					// unacceptable file type
					$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
				}
				$this->redirect('index');
			}
		}
	}

	function delete($id_file) {
		$this->Item->query('DELETE FROM items_users WHERE id_file=' . $id_file);
		$this->Item->query('DELETE FROM groups_items WHERE id_file=' . $id_file);
		if ($this->Item->query('DELETE FROM items where id_file=' . $id_file)) {
			$this->Session->setFlash('The file with id: ' . $id_file . ' has been deleted.');
			$this->redirect(array('action' => 'index', $id_file));
		}
	}

	function download($id_file) {
		$chemin = './file/';
		$file = $this->Item->query('SELECT * FROM items WHERE items.id_file= ' . $id_file);
		header("Content-disposition: attachment; filename=" . $file[0]['items']['file_name'] . "");
		header("Content-Type: application/force-download");
		header("Content-Transfer-Encoding: $file[0]['items']['type']\n");
		header("Content-Length: " . filesize($chemin . $file[0]['items']['file_name']));
		header("Pragma: no-cache");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
		header("Expires: 0");
		readfile($chemin . $file[0]['items']['file_name']);
	}

	function edit($id_file) {
		$result = $this->Item->query('SELECT users.id_user,users.name,users.surname,users.email FROM items,items_users,users WHERE items_users.id_user=users.id_user AND items_users.id_file=items.id_file and items.id_file= ' . (int)$id_file);
		$this->set('my_files', $result);
		$result1 = $this->Item->query('SELECT id_file,file_name FROM items WHERE items.id_file= ' . (int)$id_file);
		$this->set('my_file_name', $result1);
		$result2 = $this->Item->query('SELECT groups.id_group,group_name FROM groups_users,groups WHERE groups.id_group=groups_users.id_group and (groups_users.id_user= ' . (int)$this->Auth->user('id_user') . ' or groups.id_owner=' . (int)$this->Auth->user('id_user') . ' )');
		$this->set('groups', $result2);
		$result3 = $this->Item->query('SELECT groups.id_group,groups.group_name FROM groups_items,groups WHERE groups.id_group=groups_items.id_group and groups_items.id_file=' . (int)$id_file);
		$this->set('my_groups_files', $result3);
	}

	//add a user to a group
	public function add_user() {
		$data = $this->request->data;
		//pr($data);
		$email = $data['Item']['email'];
		$id_file = $data['Item']['id_file'];
		$id_user = $this->Item->query('SELECT id_user FROM users WHERE email="' . $email . '"');
		if (count($id_user) == 0) {
			$this->Session->setFlash('Please add a valid email address');
		} else {
			$this->Item->query('Insert into items_users (id_file,id_user) Values (' . $id_file . ',' . $id_user[0]['users']['id_user'] . ')');
			//$this->Item->query('update users set notified_file=notified_file + 1 where id_user='.$id_user[0]['users']['id_user']);
		}
		/*if ($this->Group->save($save)) {
		 $this->Session->setFlash('Your group has been created successfully.');
		 } else {
		 $this->Session->setFlash('Unable to create new Group.');
		 }*/
		$this->redirect(array('action' => 'edit', $id_file));
	}

	//delete a user from a group
	function delete_user($id_file, $id_user) {
		if ($this->Item->query('DELETE FROM items_users WHERE id_file=' . $id_file . ' AND id_user=' . $id_user)) {
			$this->Session->setFlash('The user with id: ' . $id_user . ' has been deleted.');
			$this->redirect(array('action' => 'edit', $id_file));
		}
	}

	//Share a file within a group 
	public function add_group() {
		$data = $this->request->data;
		//pr($data);
		$id_group = $data['Item']['group'];
		$id_file = $data['Item']['id_file'];
		$test = $this->Item->query('SELECT * FROM groups_items WHERE id_file=' . $id_file . ' AND id_group=' . $id_group);
		if (count($test) == 0) {
			$this->Item->query('INSERT INTO groups_items (id_file,id_group) VALUES (' . $id_file . ',' . $id_group . ')');
			$this->Item->query('UPDATE users SET notified_group=notified_group + 1 WHERE id_user IN (SELECT id_user FROM groups_users WHERE id_group=' . $id_group . ')');
		}
		/*if ($this->Group->save($save)) {
		 $this->Session->setFlash('Your group has been created successfully.');
		 } else {
		 $this->Session->setFlash('Unable to create new Group.');
		 }*/
		$this->redirect(array('action' => 'edit', $id_file));
	}

	//this function permit to delete the group
	function delete_group($id_file, $id_group) {
		if ($this->Item->query('DELETE FROM groups_items WHERE id_file=' . $id_file . ' AND id_group=' . $id_group)) {
			$this->Session->setFlash('The group with id: ' . $id_group . ' has been deleted.');
			$this->redirect(array('action' => 'edit', $id_file));
		}
	}

}
